package conf

import (
	"fmt"
	"os"

	"github.com/BurntSushi/toml"
	"github.com/sirupsen/logrus"
)

var (
	logTimeFormat = "2006-01-02 15:04:05"
	tomFile       = "config-local.toml"
)

func Init() error {
	// if err := parseTomlFile(); err != nil {
	// 	return err
	// }
	configSettings()
	configLogrus()
	return nil
}

func configLogrus() {
	// 设置日志输出目标为标准输出
	logrus.SetOutput(os.Stdout)
	// 设置日志级别为Info
	logrus.SetLevel(logrus.InfoLevel)
	// 创建一个TextFormatter实例
	formatter := &logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: logTimeFormat,
		ForceColors:     true, // 启用彩色输出
	}
	// 设置日志格式化器
	logrus.SetFormatter(formatter)
}

// parseTomlFile 读取配置文件，使用toml库
func parseTomlFile() error {
	// 读取并解析配置文件
	// tomFile := "config.toml"
	// tomFile := "config-local.toml"
	// 读取配置文件, 解决跑测试的时候找不到配置文件的问题，最多往上找5层目录
	for i := 0; i < 5; i++ {
		if _, err := os.Stat(tomFile); err == nil {
			break
		} else {
			tomFile = "../" + tomFile
		}
	}
	logrus.Info(os.Getwd())
	// 读取并解析配置文件
	var err error
	if _, err = toml.DecodeFile(tomFile, Config); err != nil {
		err = fmt.Errorf("解析toml文件失败: %w", err)
		logrus.WithField("方法", "conf.parseTomlFile").Error(err)
	}
	return err
}

func configSettings() {
	Config.App = app{
		Host:     "0.0.0.0",
		Port:     6666,
		PageSize: 20,
	}

	Config.Database = database{
		Host:     "localhost",
		Port:     5432,
		Username: "postgres",
		Password: "",
		Database: "quant",
		ShowSQL:  false,
		// Host:     "182.90.248.11",
		// Port:     31801,
		// Username: "root",
		// Password: "zhanyun123",
		// Database: "quant_trade",
		// ShowSQL:  false,
	}
	Config.RedisTest = redis{
		Host:     "localhost",
		Port:     6379,
		Database: 0,
	}
	Config.RedisDaily = redis{
		Host:     "localhost",
		Port:     6379,
		Database: 1,
	}
	Config.RedisScore = redis{
		Host:     "localhost",
		Port:     6379,
		Database: 2,
	}
	Config.RedisTick = redis{
		Host:     "localhost",
		Port:     6379,
		Database: 3,
	}
	Config.Http = http{
		BaseURL: "http://localhost:8080",
	}
	Config.Tencent = tencent{
		Key:      "AKIDvihV8YkiV4PWTCi23vb9WgcNvJURDpFR",
		Secret:   "2sZ7HF0ax890vqnkZv7EBxWs0vd9RWN1",
		Endpoint: "tmt.tencentcloudapi.com",
		Region:   "ap-guangzhou",
	}
}
